package cst.a526whx.mystartpro526whx.model;




import cst.a526whx.mystartpro526whx.bean.WeatherResult;
import cst.a526whx.mystartpro526whx.iface.WeatherIface;
import cst.a526whx.mystartpro526whx.listener.WeatherListener;
import cst.a526whx.mystartpro526whx.retrofitRequest.WeatherRequest;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by admin on 2017/5/16.
 */

public class WeatherModel implements WeatherIface {
     Retrofit retrofit;
     private static final String BASE_URL = "http://www.weather.com.cn/";

     public WeatherModel() {
          retrofit = new Retrofit.Builder()
                  .baseUrl(BASE_URL)
                  .addConverterFactory(GsonConverterFactory.create())
                  .build();

     }

     @Override
     public void getWeather(String cityNumber, final WeatherListener listener) {
          final WeatherRequest request = retrofit.create(WeatherRequest.class);
          Call<WeatherResult> call = request.getResult(cityNumber);
          call.enqueue(new retrofit2.Callback<WeatherResult>() {
               @Override
               public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                    if (response.isSuccessful()&&response.body()!=null)
                    {
                         listener.onResponse(response.body().getWeatherInfo());
                    }
                    else{
                         listener.onFail("解析错误");
                    }
               }

               @Override
               public void onFailure(Call<WeatherResult> call, Throwable t) {
                    listener.onFail(t.toString());
               }
          });
     }
}
